<template>
  <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
    <view class="navbar-content">
      <!-- 左侧返回按钮 -->
      <view class="navbar-left" @click="handleBack" v-if="showBack">
        <uni-icons type="back" size="20" color="#333"></uni-icons>
      </view>
      
      <!-- 中间标题 -->
      <view class="navbar-title">
        <text class="title-text">{{ title }}</text>
      </view>
      
      <!-- 右侧操作区域 -->
      <view class="navbar-right">
        <slot name="right"></slot>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'CustomNavbar',
  props: {
    title: {
      type: String,
      default: ''
    },
    showBack: {
      type: Boolean,
      default: true
    },
    backgroundColor: {
      type: String,
      default: '#ffffff'
    }
  },
  data() {
    return {
      statusBarHeight: 0,
      navBarHeight: 44
    }
  },
  mounted() {
    this.getSystemInfo()
  },
  methods: {
    getSystemInfo() {
      uni.getSystemInfo({
        success: (res) => {
          this.statusBarHeight = res.statusBarHeight || 0
          // #ifdef MP-WEIXIN
          const menuButton = uni.getMenuButtonBoundingClientRect()
          this.navBarHeight = menuButton.height + (menuButton.top - res.statusBarHeight) * 2
          // #endif
        }
      })
    },
    handleBack() {
      this.$emit('back')
      // 默认返回行为
      if (getCurrentPages().length > 1) {
        uni.navigateBack()
      } else {
        uni.switchTab({
          url: '/pages/index/index'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #ffffff;
  border-bottom: 1rpx solid #eee;
  
  .navbar-content {
    display: flex;
    align-items: center;
    height: 88rpx;
    padding: 0 30rpx;
    position: relative;
    
    .navbar-left {
      width: 80rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
    
    .navbar-title {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .title-text {
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
      }
    }
    
    .navbar-right {
      width: 80rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}

// 小程序适配
/* #ifdef MP-WEIXIN */
.custom-navbar {
  .navbar-content {
    padding-right: 190rpx; // 为小程序胶囊按钮留出空间
  }
}
/* #endif */
</style>
